package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisConvertUtil;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redis;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        //2.如果不符合，返回
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        //3.生成一个六位的验证码
        String code = RandomUtil.randomNumbers(6);
//        //4.保存验证码到session
//        session.setAttribute("code", code);
        //4. 保存验证码到redis
        //4.1 设置验证码有效期
        redis.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.验证码发送
        log.info("验证码为{}", code);
        //6.返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验
        String phone = loginForm.getPhone();
        String code = loginForm.getCode();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //1.1.校验手机号不一致，返回错误信息
            return Result.fail("手机号输入错误");
        }

        //Object codeCache = session.getAttribute("code");
        //1.2 从redis中获得验证码
        String codeCache = redis.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (codeCache == null || !code.equals(codeCache)) {
            //1.2.1.校验验证码不一致，返回错误信息
            return Result.fail("验证码输入错误");
        }
        //2.一致，根据手机号查询用户 select * from tb_user where phone = ?
        User user = query().eq("phone", phone).one();
        //User user = userMapper.selectByPhone(phone);
        //3.用户不存在，创建新用户，保存到数据库
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(8));
            //userMapper.sava(user);
            save(user);
        }
        //4.保存用户到redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        String token = String.valueOf(UUID.randomUUID(true));
        // 解决转换问题Map<String, Object> stringObjectMap = BeanUtil.beanToMap(userDTO,new CopyOptions());
        //Map<String, Object> stringObjectMap = RedisConvertUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        redis.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token,userMap);
        redis.expire(RedisConstants.LOGIN_USER_KEY + token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //把token给前端
        //6.返回OK
        return Result.ok(token);
    }
}
